#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include "cJSON.h"

//今日诗词API：www.jinrishici.com/doc

int main()
{
	CURL* client = curl_easy_init();
	char *content = NULL;
    size_t length = 0;

	FILE *fp = open_memstream(&content, &length);
    if (fp == NULL)
    {
        perror("open_memstream");
        return 1;
    }
	//设置将服务器返回的响应消息正文写入文件流
    curl_easy_setopt(client, CURLOPT_WRITEDATA, fp);
    curl_easy_setopt(client, CURLOPT_SSL_VERIFYPEER, 0);
    curl_easy_setopt(client, CURLOPT_URL, "https://v2.jinrishici.com/sentence?X-User-Token=EsJHJ/1f3WJWXJo3d7qxs3sV7GW5GZN4");
	//发送请求消息
    CURLcode error = curl_easy_perform(client);
    if (error != CURLE_OK)
    {
        printf("curl_easy_perform failed: %s\n", curl_easy_strerror(error));
        return 1;
    }
    curl_easy_cleanup(client);

	fclose(fp);

	//puts(content);
    //解析json字符串
	cJSON *json = cJSON_Parse(content);
    free(content);
    if (json == NULL)
    {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL)
        {
            fprintf(stderr, "Error before: %s\n", error_ptr);
        }
        return 2;
    }
    //使用malloc hook分配内存
    //char* jsonstr = cJSON_Print(json);

    //puts(jsonstr);
    //使用free hook释放内存
    //cJSON_free(jsonstr);

	cJSON* data = cJSON_GetObjectItem(json, "data");
	if (data)
	{
		cJSON* msg = cJSON_GetObjectItem(data, "content");
        if (cJSON_IsString(msg) && (msg->valuestring != NULL))
        {
            puts(msg->valuestring);
        }
	}
    //递归删除所有节点
    cJSON_Delete(json);

	return 0;
}
